package com.controller;

import com.DTO.MessageDTO;
import com.Exception.NormalException.ChatException.MessageTypeException;
import com.Exception.NormalException.FileExceptions.FileFormatException;
import com.Exception.NormalException.NormalException;
import com.Factory.MessageFactory;
import com.config.FileConfigure;
import com.entity.*;
import com.service.ChatRecordService;
import com.service.ChatService;
import com.service.FriendService;
import com.service.GroupUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/chat")
@Api(tags = "聊天管理器")
@CrossOrigin
public class ChatController {
    @Autowired
    private ChatService chatService;

    @Autowired
    private ChatRecordService chatRecordService;

    @Autowired
    private GroupUserService groupUserService;

    @Autowired
    private FriendService friendService;

    @Autowired
    private FileConfigure fileConfigure;

    @Autowired
    private MessageFactory messageFactory;

        @PostMapping("/sendMessageToUser")
        @ApiOperation(value = "发送消息到用户", notes = "text:文本消息，picture:图片消息，file:文件消息, voice: 语音消息, video: 视频消息")
        @ApiResponses({
                @ApiResponse(code = MessageTypeException.code, message = MessageTypeException.message),
                @ApiResponse(code = FileFormatException.code, message = FileFormatException.message)
        })
        public boolean sendMessageToUser(MessageDTO messageDTO, HttpServletResponse response) {
            // 主动发送消息的用户调用改接口，messageDTO中包含发送用户id、接收用户id、发送内容等信息
            try {
                // 对信息进行简单处理
                Message message = this.messageFactory.newMessage(messageDTO, "user");
                ChatRecord chatRecord = new ChatRecord();
                BeanUtils.copyProperties(message, chatRecord);
                this.chatService.checkMessageType(message);
                chatRecord.setFileUrl(message.getFileUrl());

                // 向数据库中保存聊天记录
                this.chatRecordService.saveRecord(chatRecord);

                // 调用方法向接收用户发送信息
                return this.chatService.sendMessageToUser(message);
            } catch (NormalException e) {
                e.setStatus(response);
                return false;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    @PostMapping(value = "/sendMessageToGroup")
    @ApiOperation(value = "发送消息到群聊")
    @ApiResponses({
            @ApiResponse(code = MessageTypeException.code, message = MessageTypeException.message),
            @ApiResponse(code = FileFormatException.code, message = FileFormatException.message)
    })
    public boolean sendMessageToGroup(MessageDTO messageDTO, HttpServletResponse response) {
            // 向群聊中发送消息的用户调用该接口，传递的参数与发送消息到用户类似
        try {
            Message message = this.messageFactory.newMessage(messageDTO, "group");
            List<User> userList = this.groupUserService.getAllUserOfGroup(message.getReceiveUserId());
            ChatRecord chatRecord = new ChatRecord();
            BeanUtils.copyProperties(message, chatRecord);
            this.chatService.checkMessageType(message);
            chatRecord.setFileUrl(message.getFileUrl());
            this.chatRecordService.saveRecord(chatRecord);

            // 与发送消息至用户不同，发送消息至群聊调用的方法不一样
            return this.chatService.sendMessageToGroup(message, userList);
        } catch (NormalException e) {
            e.setStatus(response);
            return false;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/getGroupAndFriendList")
    @ApiOperation(value = "获取该用户的好友和他加入的群聊")
    public List<Conversation> getGroupAndFriendList(Integer userId) {
        Set<User> userSet = this.friendService.getAllFriendOf(userId);
        List<Group> groupList = this.groupUserService.getAllJoinedGroup(userId);
        List<Conversation> conversationList = new ArrayList<>();
        for(User user : userSet) {
            Conversation conversation = new Conversation();
            BeanUtils.copyProperties(user, conversation);
            conversation.setType("user");
            conversationList.add(conversation);
        }
        for(Group group : groupList) {
            Conversation conversation = new Conversation();
            BeanUtils.copyProperties(group, conversation);
            conversation.setType("group");
            conversationList.add(conversation);
        }
        return conversationList;
    }

    @GetMapping("/getGroupAndFriendListByName")
    @ApiOperation(value = "根据名字模糊查询该用户的好友和他加入的群聊")
    public List<Conversation> getGroupAndFriendListByName(Integer userId, String name) {
        List<User> userList = this.friendService.getFriendByName(userId, name);
        List<Group> groupList = this.groupUserService.getAllJoinedGroupByName(userId, name);
        List<Conversation> conversationList = new ArrayList<>();
        for(User user : userList) {
            Conversation conversation = new Conversation();
            BeanUtils.copyProperties(user, conversation);
            conversation.setType("user");
            conversationList.add(conversation);
        }
        for(Group group : groupList) {
            Conversation conversation = new Conversation();
            BeanUtils.copyProperties(group, conversation);
            conversation.setType("group");
            conversationList.add(conversation);
        }
        return conversationList;
    }
}
